package com.ruoyi.system.service;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SubtabulationVO;
import com.ruoyi.system.mapper.SubtabulationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZGL
 * @description
 * @className SubtabulationService
 * @date 2022/8/10 下午 04:19
 */
@Service
public class SubtabulationService {

    @Autowired
    private SubtabulationMapper mapper;

    /**
     * 根据主表，删除子表数据
     * @param buildKey
     * @param delData
     * @throws Exception
     */
    public void delete(String buildKey,List delData) throws Exception {
        if(delData==null || delData.size()<=0){
            return;
        }
        ArrayList<Map<String,Object>> delDatas =JSONObject.parseObject(JSONObject.toJSONString(delData),ArrayList.class);
        //获取当前模块下，所有子表
        List<SubtabulationVO> subtabulationVOS = mapper.SubtabulationCS(buildKey);
        if (subtabulationVOS.size() > 0) {
            //循环删除子表记录
            Map<String,Object> param =null;
            //获取主表中的值
            ArrayList<Object> pkValues = null;
            for (int i = 0; i < subtabulationVOS.size(); i++) {
                //获取主表中的值
                pkValues = getPkValues(delDatas, subtabulationVOS.get(i).getPrimaryTableKey());
                if(pkValues==null || pkValues.size()<=0){
                    continue;
                }
                param=new HashMap<>();
                param.put("tablename",subtabulationVOS.get(i).getTablename());
                //子表关联字段__存在子表的情况下
                param.put("fk",subtabulationVOS.get(i).getForeignKey());
                param.put("pkIds",pkValues);
                mapper.deleteChild(param);
            }
        }
    }

    /**
     * 获取主表的主键值
     * @param delDatas
     * @param primaryTableKey
     * @return
     */
    private ArrayList<Object> getPkValues(ArrayList<Map<String,Object>> delDatas,String primaryTableKey){

        if(delDatas==null || delDatas.size()<=0 || StringUtils.isEmpty(primaryTableKey)){
            return null;
        }

        //结果
        ArrayList<Object> result=new ArrayList<>();
        /**
         * 遍历获取主表中的数据
         */
        for(Map<String,Object> item:delDatas){
            if(StringUtils.isNotEmpty(String.valueOf(item.get(primaryTableKey)))){
                result.add(item.get(primaryTableKey));
            }
        }
        return result;
    }
}
